package com.xvyy.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateCrtKey;

/**
 * ClassName: WxAutoConfiguration
 * Package: com.xvyy.tingshu.user.config
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/1/13 - 12:49
 * @Version: v1.0
 */
@Configuration
@EnableConfigurationProperties(WxProperties.class)
public class WxAutoConfiguration {


/*    @Value("${wechat.login.appId}")
    private String appId;
    @Value("${wechat.login.appSecret}")
    private String appSecret;*/


    /**
     * @Description: 配置一个WxMaService的实现类
     * @return WxMaService
     */
    @Bean
    public WxMaService wxMaService(WxProperties wxProperties) {
        //1. 定义一个MaServiceImpl的实现类
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();

        //2. 给这个实现类设置appId和appSecret
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxProperties.getAppSecret());
        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        return wxMaService;
    }

    /**
     * @Description: 配置一个RsaSigner的实现类
     * @return RsaSigner
     */
    @Bean
    public RsaSigner rsaSigner() {

        //1. 获取 tingshu.jks证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");

        //2. 获钥匙工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());

        //3. 获取钥匙对
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());

        //4. 获取私钥
        RSAPrivateCrtKey aPrivate = (RSAPrivateCrtKey) keyPair.getPrivate();

        //5. 返回RsaSigner对象
        return new RsaSigner(aPrivate);
    }
}
